package com.bt.lms.ui.page.sys.user.action;

import com.alibaba.fastjson.JSONObject;
import com.bt.lms.constants.BOConstant;
import com.bt.lms.constants.SysBizTypeConstant;
import com.bt.lms.entity.User;
import com.bt.lms.network.msg.RespMsg;
import com.bt.lms.ui.page.sys.utils.ArrayUtils;
import com.bt.lms.ui.page.sys.utils.NetWorkUtils;
import com.bt.lms.ui.page.sys.vo.UserTableViewVo;
import com.bt.lms.ui.vo.PageSkipInfo;
import com.bt.lms.ui.page.sys.utils.Encode;
import com.bt.lms.ui.page.sys.ServerInfo;
import com.bt.lms.network.msg.ReqMsg;
import com.bt.lms.ui.page.sys.user.PageDetails;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;

/**
 * 查看详情事件
 */
public class ULDetailsAction implements EventHandler<MouseEvent> {


    /**
     * 要查看的用户信息
     */
    private final UserTableViewVo userTableViewVo;

    /**
     * 界面跳转信息
     */
    private final PageSkipInfo pageSkipInfo;

    /**
     * 构建添加用户按钮事件
     *
     * @param pageSkipInfo 界面跳转信息
     * @param userTableViewVo 要查看的用户id
     */
    public ULDetailsAction(PageSkipInfo pageSkipInfo, UserTableViewVo userTableViewVo) {
        this.pageSkipInfo = pageSkipInfo;
        this.userTableViewVo = userTableViewVo;
    }

    /**
     * 事件实现
     * 1.跳转界面（个人部分跳转 + 位置变化）
     *
     * @param event the event which occurred
     */
    @Override
    public void handle(MouseEvent event) {

        //组装网络消息包
        //1.发送请求
        //1.1 组装消息包
        ReqMsg reqMsg = Encode.encodeToMsg(userTableViewVo, SysBizTypeConstant.USER_DETAILS);
        byte[] sumBytes = reqMsg.toBytes();
        //1.2 组网
        Socket socket = pacNet();
        OutputStream out;
        try {
            out = socket.getOutputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //1.3 发网，返回结果
        boolean res = sendReq(out, sumBytes);
        //判断是否发送成功
        if (res) {
            try {
                InputStream in = socket.getInputStream();
                //接收响应
                List<byte[]> bufS = NetWorkUtils.receive(in);
                //处理结果
                byte[] respBytes = ArrayUtils.joinBytes(bufS);
                //结果转消息
                RespMsg respMsg = RespMsg.toRespMsg(respBytes);
                //比较状态
                short status = respMsg.getStatus();
                if (status == RespMsg.NETWORK_STATUS_NORMAL) {
                    //资源关闭
                    in.close();
                    out.close();
                    socket.close();
                    //成功发送，处理结果集
                    String data = respMsg.getData();
                    User user = JSONObject.parseObject(data, User.class);
                    finish(user);
                } else {
                    String failStr = "未找到该用户，请稍候重试。";
                    hintFrame(failStr);//提示框
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            hintFrame("网络异常，请检查网络或联系客服。");//提示框
        }
    }

    /**
     * 程序结束
     */
    private void finish(User user) {

        Pane pane = pageSkipInfo.getPane();
        Integer index = pageSkipInfo.getIndex();

        PageDetails pageDetails = new PageDetails(user, pageSkipInfo);
        //界面跳转
        ObservableList<Node> children = pane.getChildren();
        children.set(index, pageDetails);
    }

    /**
     * 发送请求
     *
     * @param out 输出流
     * @param bytes  要发送的数据
     * @return 发送结果
     */
    private boolean sendReq(OutputStream out, byte[] bytes) {

        try {
            out.write(bytes);
            out.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return true;

    }

    /**
     * 组网
     *
     * @return 网
     */
    private Socket pacNet() {

        String ip = ServerInfo.IP;
        int port = ServerInfo.PORT;

        Socket socket;
        try {
            socket = new Socket(ip, port);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return socket;
    }

    /**
     * 程序终止
     * 弹窗提示
     *
     * @param result 终止提示
     */
    private void hintFrame(String result) {
        //提示弹窗
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        //错误提示
        alert.setTitle("失败");
        alert.setHeaderText(null);
        alert.setContentText(result);
        alert.showAndWait();
    }

}
